import axios from 'axios'
import QS from 'qs'
// import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, getTokenTTL, removeToken, removeUser } from './auth'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
})
// request interceptor/*  */
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (!config.url.endsWith('/upms/oauth/token')) {
      // 登录接口不需要传token
      config.headers['Authorization'] = 'Bearer ' + getToken()
      // 刷新TOKEN
      const ttl = getTokenTTL()
      // console.log('token ttl=', ttl)
      if (ttl && ttl < 600 && ttl > 0) {
        // 10分钟内即将到期，而且TOKEN有效，刷新token
        store.dispatch('user/REFRESH_TOKEN')
      }
    }

    config.headers['Tenant-Not-Hold'] = true
    // 如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
    if (config.method.toLowerCase() === 'get') {
      config.paramsSerializer = function (params) {
        return QS.stringify(params, { arrayFormat: 'repeat' })
      }
    }
    config.headers['lang'] = store.getters.language
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    if (res.code === 401 || res.code === 403) {
      store.dispatch('user/RESET_TOKEN')
      router.go(0)
      // Message({
      //   message: 'token过期，请重新登录！',
      //   type: 'error',
      //   duration: 5 * 1000,
      // })
      return
    }
    return res
  },
  (error) => {
    console.log(error.request) // for debug
    if (error.request.status === 403) {
      store.dispatch('user/RESET_TOKEN')
      router.go(0)
      // Message({
      //   message: 'token过期，请重新登录！',
      //   type: 'error',
      //   duration: 5 * 1000,
      // })
      return error.response.data
    } else if(error.request.status === 401) {
      // Fix BUG: 登录时无法提示正确的提示语问题
      return error.response.data
    }

    // Message({
    //   message: JSON.parse(error.request.response).message,
    //   type: 'error',
    //   duration: 1 * 1000,
    // })
    return Promise.reject(error)
  }
)
export const FileService = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
})
FileService.interceptors.request.use(
  (config) => {
    config.responseType = 'arraybuffer'
    // if (store.getters.token) {
    config.headers['Authorization'] = 'Bearer ' + getToken()
    // }
    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  }
)
export const QrcodeService = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
})
QrcodeService.interceptors.request.use(
  (config) => {
    config.responseType = 'blob'
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  }
)
export default service
